from info.utils.constants import HOME_PAGE_MAX_NEWS
from info.modules.home import home_blu
from flask import render_template, current_app, session, jsonify, abort, request

# 使用蓝图来注册路由
from info.utils.models import User, News, Category
from info.utils.response_code import RET, error_map


@home_blu.route('/')
def index():
    # 判断用户是否已登入
    user_id = session.get('user_id')
    user = None

    if user_id:
        try:
            user = User.query.get(user_id)
            print(1)
        except BaseException as e:
            current_app.logger.error(e)

    # 查询点击量前10的新闻
    rank_list = []
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(5).all()
    except BaseException as e:
        current_app.logger.error(e)

    rank_list = [news.to_basic_dict() for news in rank_list]

    # 查看所有分类数据
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    user = user.to_dict() if user else None
    return render_template("index.html", user=user, rank_list=rank_list, categories=categories)



@home_blu.route('/favicon.ico')
def favico():
    response = current_app.send_static_file("news/favicon.ico")

    return response


@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid')
    cur_page = request.args.get('cur_page')
    per_count = request.args.get('per_count', HOME_PAGE_MAX_NEWS)


    if not all([cid,cur_page,per_count]):
        return  jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    try:
        cid=int(cid)
        cur_page=int(cur_page)
        per_count=int(per_count)
    except BaseException as e :
        current_app.logger.error(e)
        return  jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    filter_list=[]

    if cid!=1:
        filter_list.append(News.category_id==cid)

    # 根据分类 ，页码查询新闻数据 根据新闻发布时间进行排序

    try:
        pn=News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page,per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return  jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])

    data={ 'news_list':[ news.to_basic_dict() for news in pn.items],
           'total_page':pn.pages}

    return jsonify(error=RET.OK,errmsg=error_map[RET.OK],data=data)